<template>
  <div class="app-container logistics">
    <div class="head-container">
      <div class="head-container-tools">
        <template v-if="crud.props.searchToggle">
          <span>调剂时间: </span>
          <el-date-picker
            v-model="query.adjustTime"
            type="daterange"
            range-separator="至"
            size="small"
            class="filter-item charges-date-picker"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 240px"
          >
          </el-date-picker>
          <span>支付时间: </span>
          <el-date-picker
            v-model="query.payTime"
            type="daterange"
            range-separator="至"
            size="small"
            class="filter-item charges-date-picker"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 240px"
          >
          </el-date-picker>
          <el-input
            v-model="query.patientName"
            placeholder="患者姓名或手机号"
            style="width: 160px"
            class="filter-item"
            size="small"
          />
          <el-input
            v-model="query.userName"
            placeholder="收货人"
            style="width: 160px"
            class="filter-item"
            size="small"
          />
          <el-input
            v-model="query.docName"
            placeholder="医生姓名"
            style="width: 150px"
            class="filter-item"
            size="small"
          />
          <el-input
            v-model="query.orderNo"
            placeholder="订单编号"
            style="width: 150px"
            class="filter-item"
            size="small"
          />
          <el-select
            v-model='query.orderCondition'
            clearable
            size='small'
            placeholder='物流状态'
            class='filter-item'
            style='width: 120px'
            @change="crud.toQuery"
          >
            <template v-for='item in oConditionList'>
              <el-option
                :key='item.id'
                :label='item.text'
                :value='item.id'
              />
            </template>
          </el-select>
          <rrOperation :crud="crud" />
        </template>
        <crudOperation>
          <!-- 合并发货 -->
          <template v-if="!isUnify&&!isPostCount">
            <el-button
              slot="left"
              class="filter-item"
              type="primary"
              icon="el-icon-add"
              size="mini"
              v-permission="['admin','logistics:unifDeliver']"
              @clck="unificationPost"
            >合并发货</el-button>
            <el-button
              v-permission="['admin','logistics:batchDeliver']"
              @click="unificationPostCount"
              slot="left"
              class="filter-item"
              type="primary"
              icon="el-icon-add"
              size="mini"
            >批量发货</el-button>
          </template>
          <template v-else>

            <template v-if="isUnify">
              <el-button
                slot="left"
                class="filter-item"
                type="primary"
                icon="el-icon-add"
                size="mini"
                @click="unificationPostCancel"
              >取消</el-button>
              <el-button
                slot="left"
                class="filter-item"
                type="primary"
                icon="el-icon-add"
                size="mini"
                @click="postUnifyData"
              >合并发货
              </el-button>
            </template>

            <template v-if="isPostCount">
              <el-button
                slot="left"
                class="filter-item"
                type="primary"
                icon="el-icon-add"
                size="mini"
                @click="unificationPostCountCancel"
              >取消</el-button>
              <el-button
                slot="left"
                class="filter-item"
                type="primary"
                icon="el-icon-add"
                size="mini"
                :loading="isLoading"
                @click="postCountUnifyData"
              >批量发货
              </el-button>
            </template>

          </template>
          <span slot="left" v-if="isUnify">（默认选择第一个订单的发货地址）</span>
        </crudOperation>
      </div>
    </div>

    <el-table
      @selection-change="handleSelectionChange"
      :row-class-name="rowClass"
      v-loading="crud.loading"
      class="logistics-table"
      :data="crud.data"
      ref="table"
    >
      <el-table-column
        v-if="isUnify"
        width="55">
        <template slot-scope="scope">
          <template v-if="scope.row.orderType == 2&&scope.row.deliveryType == 1">
            <el-checkbox v-model="scope.row.isChecked" @change="unifySelect(scope.row)"></el-checkbox>
          </template>
        </template>
      </el-table-column>
      <template v-if="isPostCount">
        <el-table-column type="selection" width="55"></el-table-column>
      </template>
      <el-table-column v-if="columns.visible('orderType')" label="订单来源" prop="orderType" width="160">
        <template slot-scope="scope">
          <template v-if="scope.row.orderType == 1">
            <span>本地处方</span>
          </template>
          <template v-else>
            <span>云享处方-{{ scope.row.source }}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column  label="订单时间" prop="orderTime" width="136">
        <template  slot-scope="scope">{{ scope.row.orderTime }}</template>
      </el-table-column>
      <el-table-column  label="开方医生" prop="docName"></el-table-column>
      <el-table-column  label="患者姓名" prop="patientName"></el-table-column>
      <el-table-column  label="收货人" prop="username">
        <template  slot-scope="{row}" >
          <template v-if="row.orderAddress && row.deliveryType === 1">
            <el-tag class="exchange" type="info" >{{ row.orderAddress.username }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column  label="收货号码" prop="phone" width="100">
        <template  slot-scope="{row}" >
          <template v-if="row.orderAddress && row.deliveryType === 1">
            <span>{{ row.orderAddress.phone }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column  label="收货地址" prop="address" width="200">
        <template  slot-scope="{row}" >
          <template v-if="row.orderAddress && row.deliveryType === 1">
            <span>{{ row.orderAddress.province }}{{ row.orderAddress.city }}{{ row.orderAddress.area }}{{ row.orderAddress.address }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('orderStatus')" label="物流状态" prop="orderStatus">
        <template slot-scope="{row}">
          <template v-if="row.orderCondition == 3 && row.payStatus != 4">
            <template v-if="row.deliveryType === 2">
              <el-tag class="exchange" type="danger">待自取</el-tag>
            </template>
            <template v-else>
              <el-tag class="exchange" type="danger">待发货</el-tag>
            </template>
          </template>
          <template v-else-if="row.orderCondition == 4">
            <el-tag type="success">已完成</el-tag>
          </template>
          <template v-else-if="row.orderCondition == 5">
            <el-tag type="success">已发货</el-tag>
          </template>
          <template v-else-if="row.orderCondition == 7 && row.payStatus != 4">
            <el-tag type="danger">已拦截</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('remark')" label="订单备注" prop="remark" width="180">
        <template slot-scope="{row}">{{ row.remark }}</template>
      </el-table-column>
      <el-table-column v-if="columns.visible('nextRemark')" label="延期原因" prop="nextRemark" width="100">
        <div slot-scope="{row}">
          <template v-if="row.nextRemark">
            <el-button
              @click="onShowNextRemark(row)"
              type="text"
            >查看</el-button>
          </template>
        </div>
      </el-table-column>
      <el-table-column  label="物流单号" prop="lastMailNo" width="180">
        <template  slot-scope="scope">{{ scope.row.lastMailNo }}</template>
      </el-table-column>
      <el-table-column  label="发货时间" prop="lastMailTime" width="180">
        <template  slot-scope="scope">{{ scope.row.lastMailTime }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">

          <template v-for="item in scope.row.btns">
            <el-button
              @click="onRowHandle(item)"
              :key="item.id"
              type="text"
            >{{ item.text }}</el-button>
          </template>

          <template v-if="scope.row.downBtns.length > 0">
            <el-dropdown class="logistics-dropdown">
              <span class="el-dropdown-link el-logistics">
                <span class="text">更多</span>
                <i class="el-icon-arrow-down"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <template v-for="item in scope.row.downBtns">
                  <el-dropdown-item :key="item.id">
                    <el-button
                      @click="onRowHandle(item)"
                      type="text"
                    >{{ item.text }}</el-button>
                  </el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination />

    <!-- 发货窗口 -->
    <go-deliver ref="deliver"></go-deliver>
    <operateForm
      @refresh="crud.refresh()"
      @goDeliver="onGoDeliver"
      :isDeliver="false"
      ref="operateForm"
    >
    </operateForm>
    <!-- 合并发货前确认 -->
    <deliver-confirm ref="deliverConfirm" @confirm="postUnifyDataOk" />
    <!-- 合并发货窗口 -->
    <go-unify-deliver ref="deliverunify"></go-unify-deliver>
    <!-- 查看物流单 -->
    <go-post-deliver ref="deliverPost"></go-post-deliver>
    <!-- 打印 -->
    <printSend ref="printSend"></printSend>
    <!-- 延期发货 -->
    <delay-deliver ref="delayDeliver" @success="crud.refresh()"/>
  </div>
</template>

<script>
  import operateForm from "@/views/charges/clinicCharges/module/operateForm";
  import { updateOrder,updateOrderr, addOrderList} from "@/api/charges/prescription";
  import { formatMoney, getPatientSex, phoneData } from "@/utils/index";
  import goUnifyDeliver from "./module/goUnifyDeliver";
  import deliverConfirm from "./module/deliverConfirm";
  import CRUD, { presenter, header } from "@crud/crud";
  import goPostDeliver from "./module/goPostDeliver";
  import crudOperation from '@crud/CRUD.operation';
  import printSend from "@/views/charges/print";
  import rrOperation from "@crud/RR.operation";
  import goDeliver from "./module/goDeliver";
  import pagination from "@crud/Pagination";
  import delayDeliver from "./module/delay";
  import { mapGetters } from "vuex";

  let defaultCrud = CRUD({
    query: {
      pharmacyId: null,
      payTime: null,
      adjustTime: null,
      patientName: null,
      docName: null,
      orderNo: null,
      deliveryType:null,
      orderCondition:null,
      userName: null,
      isFlag: 1,
    },
    hideColumns: ["patientSex","patientAge","phone","pstType","orderTime", "orderNo"],
    url: "api/recipel/getPrescriptions",
    queryOnPresenterCreated: false,
    sort: ['next_time,desc', 'adjust_time,desc'],
    title: "发货管理"
  });

  export default {
    name: "logistics",
    mixins: [ presenter(defaultCrud), header() ],
    components: {
      crudOperation,
      rrOperation,
      operateForm,
      pagination,
      printSend,
      goDeliver,
      goUnifyDeliver,
      goPostDeliver,
      deliverConfirm,
      delayDeliver,
    },
    data() {
      return {
        pstTypeList: [
          {id: 0, text: "西药及中成药"},
          {id: 1, text: "饮片"},
          {id: 2, text: "颗粒"},
          {id: 3, text: "打粉"},
          {id: 4, text: "制丸"},
          {id: 5, text: "膏方"},
        ],
        oConditionList: [
          { id: 3, text: "待发货/待自取" },
          { id: 4, text: "已完成" },
          { id: 5, text: "已发货" },
          // { id: 7, text: "已拦截" },
        ],
        status: 0,
        isUnify:false,
        unifyDataList:[],
        unifyOrderNoList:[],
        postCountList:[],
        isPostCount:false,
        isLoading:false,
      }
    },
    computed: {
      ...mapGetters(["roles"]),
    },
    created() {
      this.$store.dispatch("GetInfo").then(res => {
        this.query.pharmacyId = res.pharmacyId;
        this.crud.toQuery();
      });
    },
    mounted() {
      let date = new Date();
      let date2 = new Date(date.getTime() - 3 * 24 * 60 * 60 * 1000);
      if(!this.query.adjustTime) {
        this.query.adjustTime = [
          this._dateToString(date2),
          this._dateToString(date)
        ];
      }
    },
    methods: {
      getPatientSex, formatMoney, phoneData,
      [CRUD.HOOK.dataLoadSuccess](crud, data) {
        let btns;
        data.forEach(item => {
          var index = this.unifyOrderNoList.indexOf(item.orderNo);
          if(index > 0){
            item.isChecked = true;
          }else{
            item.isChecked = false;
          }
          btns = this._operateBtns(item.payStatus, item);
          if(btns.length > 2) {
            item.btns = btns.slice(0, 2);
            item.downBtns = btns.slice(2);
          } else {
            item.btns = btns;
            item.downBtns = [];
          }
        });
      },
      handleSelectionChange(val) {
        this.postCountList = [];
        this.postCountList = val;
      },
      // 批量发货
      unificationPostCount(){
        this.isPostCount = true;
        this.isUnify = false;
        // this.query.deliveryType = 1;
        // this.query.orderType = 2;
        // this.crud.refresh();
      },
      // 统一发货
      unificationPost(){
        this.isUnify = true;
        this.isPostCount = false;
      },
      // 批量发货 发货
      postCountUnifyData(){
        if(this.postCountList.length > 0) {
          this.isLoading = true;
          var pList  = [];
          this.postCountList.forEach(a => {
            var dd = {'areaCode':null,'cityCode':null,'consignment':null,'destAddress':null,'destCity':null,'destDistrict':null,'destName':null,'destPhone':null,'destProvince':null,'provinceCode':null,'expressType':null,'statementValue':null,'orderNo':null,'parcelWeighs':null,'payMethod':null,'productCode':null,};
            var ads = a.orderAddress;
            console.log('a------->',a);
            console.log('------->',ads);
            dd.areaCode = ads.areaCode;
            dd.cityCode = ads.cityCode;
            dd.consignment = "ZY";
            dd.destAddress = ads.address;
            dd.destCity = ads.city;
            dd.destDistrict = ads.area;
            dd.destName = ads.username;
            dd.destPhone = ads.phone;
            dd.destProvince = ads.province;
            dd.provinceCode = ads.provinceCode;
            dd.expressType = "2";
            dd.statementValue = "0";
            dd.orderNo = a.orderNo;
            dd.parcelWeighs = '0';
            dd.payMethod = '1';
            dd.productCode = 'CHINESE_HERBAL';

            pList.push(dd);
          });
          addOrderList(pList).then(() => {
            this.isPostCount=false;
            this.isUnify=false;
            this.crud.refresh();
            this.postCountList = [];
            this.isLoading = false;
            this._success();
          }).catch(() => {
            this.submitLoading = false;
          });
        } else {
          this.$message.error("请选择要提交的数据!");
        }
      },
      // 统一发货 取消
      unificationPostCancel(){
        this.isUnify = false;
        this.isPostCount = false;
        this.unifyDataList.forEach(e => {
          e.isChecked = false;
        });
        this.unifyDataList = [];
        this.unifyOrderNoList = [];
      },
      // 批量发货 取消
      unificationPostCountCancel(){
        this.isPostCount = false;
        this.isUnify = false;
        // this.query.deliveryType = null;
        // this.query.orderType = null;
        // this.crud.toQuery();
      },
      // 统一发货 选中
      unifySelect(row) {
        if(row.isChecked){
          this.unifyDataList.push(row);
          this.unifyOrderNoList.push(row.orderNo);
        }else{
          var index = this.unifyDataList.indexOf(row)
          this.unifyDataList.splice(index,1)
          this.unifyOrderNoList.splice(index,1)
        }
        console.log(this.unifyDataList);
        console.log(this.unifyOrderNoList);
      },
      // 统一发货 发送物流
      postUnifyData() {
        if(this.unifyDataList.length > 0) {
          this.$refs.deliverConfirm.open(this.unifyDataList);
        } else {
          this.$message.error("请选择要提交的数据!");
        }
      },
      // 确认合并
      postUnifyDataOk() {
        var orderNos = this.unifyOrderNoList[0];
        this.onGoDeliverUnify(orderNos);
      },
      resetUnifyData() {
        this.isUnify = false;
        this.unifyOrderNoList=[];
        this.unifyDataList = [];
      },
      onOperateRow(operate, id) {
        switch(operate) {
          case 6:
            // 打印
            this.$refs.printSend.open(id);
            break;
          default:
            this.$refs.operateForm.open(operate, id,2,99);
            break;
        }
      },
      // 单独发货
      onGoDeliver(order) {
        let { orderNo } = order;
        this.$refs.deliverunify.open(orderNo, orderNo, [order]);
      },
      onGoPostDeliver(orderNo) {
        this.$refs.deliverPost.open(orderNo);
      },
      onGoDeliverUnify(orderNo) {
        var orderNos = this.unifyOrderNoList.join(',');
        this.$refs.deliverunify.open(orderNo,orderNos,this.unifyDataList);
      },
      onUpdateOrder(id) {
        updateOrder(id).then(() => {
          _success();
        });
      },
      onOkOrder(orderNo) {

        updateOrderr(orderNo).then(() => {
          this.$notify({
            title: "操作成功",
            type: "success"
          });
          this.crud.toQuery();
        });
      },
      onRowHandle(btn) {
        btn.handle.apply(this, btn.params)
      },
      _operateBtns(payStatus, row) {
        let { orderNo, id, deliveryType, orderCondition, orderType,lastMailNo } = row;
        let res = [];
        res.push({ text: "查看", permission: "logistics:detail", handle: this.onClickOrder, params: [row,99999] });
        if(payStatus != 4) {
          res.push({ text: "打印", permission: "logistics:print", handle: this.onPrintDetails, params: [row] });
        }
        if(deliveryType == 1) {
          // 已完成,邮寄
          if(orderType == 2) {
            if(lastMailNo){
              res.push({ text: "查看物流单", permission: "logistics:showDeliver", handle: this.onGoPostDeliver, params: [orderNo] });
            }
            res.push({ text: "发货", permission: "logistics:addOrder", handle: this.onGoDeliver, params: [row] });
          } else {
            // if(orderCondition == 3||orderType == 2) {
            if(orderCondition == 3) {
              res.push({ text: "确认发货", handle: this.onOkOrder, params: [orderNo] });
            }
          }
        }
        if(deliveryType == 2) {
          // 已完成,自提
          if(orderCondition == 3) {
            res.push({ text: "确认自提", handle: this.onOkOrder, params: [orderNo] });
          }
        }
        res.push({ text: "延期发货", permission: "logistics:delay", handle: this.onDelay, params: [row] });

        // 权限检查，剔除无权访问的操作
        let btns = [];
        let permissionRoles;
        let hasPermission;
        res.forEach(item => {
          if(!item.permission) {
            btns.push(item);
            return;
          }
          permissionRoles = ["admin", item.permission];
          hasPermission = this.roles.some(role => {
            return permissionRoles.includes(role);
          });
          if(hasPermission) {
            btns.push(item);
          }
        });

        return btns;
      },
      onClickOrder(operate){
        this.$refs.operateForm.open(operate, 99999,2,99);
      },
      onPrintDetails(row) {
        this.$refs.printSend.open(row.id);
      },
      onDelay(row) {
        this.$refs.delayDeliver.open(row);
      },
      getInfoNum(infos) {
        let res = 0;
        infos.forEach(item => {
          if(item.orderCondition != 5) {
            res ++;
          }
        });
        return res;
      },
      _success() {
        this.$notify({
          title: "操作成功",
          type: "success"
        });
        this.crud.refresh();
      },
      _dateToString(date) {
        return date.getFullYear() + "-" + (date.getMonth()> 8 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1)) + "-" +(date.getDate() > 8 ? (date.getDate()) : "0" + (date.getDate()));
      },
      onShowNextRemark(row) {
        this.$refs.delayDeliver.showDetail(row);
      },
      rowClass({ row }) {
        let { nextRemark, nextFlag } = row;
        let res = {};
        if(nextRemark && nextFlag != 1) {
          res = "tr-td-red";
        }
        return res;
      }
    }
  }
</script>

<style src="../../ordermag/local/style/index.css"></style>

<style>
  .logistics-dropdown {
    margin-left: 10px;
  }

  .logistics-dropdown .el-logistics {
    cursor: pointer;
  }

  .logistics-dropdown .el-logistics .text {
    color: #1890ff;
    font-size: 12px;
  }

  .logistics-dropdown .el-logistics .el-icon-arrow-down {
    color: #1890ff;
  }

  .logistics-table tbody tr.tr-td-red {
    background-color: #fdf5e6;
  }

  .logistics-table tbody tr.tr-td-red:hover > td {
    background-color:#fdf5e6!important
  }
</style>
